import wepy from 'wepy'
import API from '@/api'

export default class CommonMixin extends wepy.mixin {
  data = {
    // 剪贴板入场
    clipboardData: null,

    // 省选择器
    provinceList: ['粤', '京', '津', '沪', '渝', '冀', '豫', '云', '辽', '黑', '湘', '皖', '鲁', '新', '苏', '浙', '赣', '鄂', '桂', '甘', '晋', '蒙', '陕', '吉', '闽', '贵', '青', '藏', '川', '宁', '琼'],
    localAppSetting: {}
  }
  computed = {
    HOST() {
      return API.HOST
    }
  }
  methods = {
    getWxPhone: this.getWxPhone,
    navigate: this.navigate,
    openAppSetting: this.openAppSetting,
    getAppSetting: this.getAppSetting,
    getSavePhoto: this.getSavePhoto
  }
  // 验证车牌号
  VerifyCarNum(carNum) {
    const regExp = /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([A-Z0-9]{5}[A-Z0-9])|([A-Z0-9]([A-HJ-NP-Z0-9])[A-Z0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/
    return regExp.test(carNum)
  }
  // 新验证后六位
  VerifyLastSix(value) {
    if (!value) return false
    return value.length === 6
  }
  // 验证手机号
  VerifyPhone(value) {
    const regExp = /^1[2|3|4|5|6|7|8|9][0-9]\d{8}$/
    return regExp.test(value)
  }
  // 轻提示
  Toast(title, icon = 'none', duration = 1500) {
    wepy.showToast({
      title,
      icon,
      duration
    })
  }

  navigate(path, options) {
    this.$navigate(path, options)
  }

  /**
   * 打开系统设置
   */
  openAppSetting(e) {
    this.localAppSetting = e.detail.authSetting
  }

  /**
   * 获取系统设置
   */
  async getAppSetting() {
    const res = await wepy.getSetting()
    if (res.errMsg !== 'getSetting:ok') throw '用户设置信息获取失败'
    this.localAppSetting = res.authSetting
    this.$apply()
  }

  async getWxPhone(e) {
    if (e.detail.errMsg !== 'getPhoneNumber:ok') return
    const {
      code
    } = await wepy.wx.login()
    let sessionKeyRes = await this.getSessionKey(code)
    if (!sessionKeyRes) return
    const sessionKey = sessionKeyRes.result.session_key
    const res = await API.GetWxUserPhone({
      wx_union_user_id: this.localWxUser ? this.localWxUser.id : undefined,
      app_name: config.APP_NAME,
      encryptedData: e.$wx.detail.encryptedData,
      iv: e.$wx.detail.iv,
      sessionKey
    }, null, false)
    if (res.code !== 200) return

    const mobile = res.result.purePhoneNumber
    this.setStorage('LOCAL_MOBILE', mobile)
    this.storeLocalMobile(mobile)

    if (this.authCompleted) this.authCompleted()
    return mobile
  }

  // 获取保存到相册权限
  async getSavePhoto() {
    await wepy.authorize({
      scope: 'scope.writePhotosAlbum'
    }).then(() => {
      this.getAppSetting()
    }).catch(() => {
      wepy.showModal({
        title: '提示',
        content: `暂未授权，请点击“打开设置页”允许“保存到相册”`,
        showCancel: false,
        confirmText: '好的',
        confirmColor: '#f00'
      })
    })
  }

  onShow() {}

  onLoad() {}
}
